angular.module('Caltech').controller('certificateItemController', function ($scope, Restangular, $state, $stateParams, $filter, Statuses, Constants, toaster) {
    'use strict';

    $scope.username = Constants.accountInfo.fullName;

    $scope.model = {
        customer: {
        },
        equipmentId: 0,
        calibrationCycle: 0,
        calibrationDate: new Date(),
        standards: [],
        createdBy: Constants.accountInfo.id,
        updatedBy: Constants.accountInfo.id
    };

    $scope.updateEquipment = function (equipment) {
        $scope.model.equipmentId = equipment.id;
        $scope.model.modelNumber = equipment.modelNumber;
        $scope.model.serialNumber = equipment.serialNumber;
        $scope.model.manufacturer = equipment.manufacturer;
        $scope.model.description = equipment.name;
        $scope.model.assetNumber = equipment.assetNumber;
        $scope.model.procedure = equipment.Procedure;
    };

    if ($stateParams.equipmentId > 0) {
        $scope.model.equipmentId = $stateParams.equipmentId;
        Restangular.one('equipment', $stateParams.equipmentId).get().then(function (item) {
            $scope.updateEquipment(item);
        });
    }

    if ($stateParams.customerId > 0) {
        Restangular.one('customer', $stateParams.customerId).get().then(function (item) {
            $scope.updateCustomer(item);
        });
    }

    if ($stateParams.poNo) {
        $scope.model.poNumber = $stateParams.poNo;
    }

    if ($stateParams.woNo) {
        $scope.model.workOrderNo = $stateParams.woNo;
    }

    $scope.updateCustomer = function (customer) {
        if (!customer) {
            $scope.model.customer = {};
        } else if (typeof (customer) === 'object') {
            $scope.model.customer = customer;
        }
    };

    $scope.pageNumber = $scope.model.standards.length >= 20 ? 2 : 1;

    $scope.getCustomerList = function (name) {
        return Restangular.all('customer').getList({
            name: name
        });
    };

    $scope.getProcedureList = function (name) {
        return Restangular.all('procedure').getList({
            name: name
        });
    };

    $scope.updateProcedure = function (procedure) {
        $scope.model.procedure = procedure.procedureName;
        $scope.model.standards = procedure.items;
        $scope.model.approvedBy = procedure.approveUser.fullName;
        $scope.model.temperature = procedure.temperature;
        $scope.model.relativeHumidity = procedure.humidity;
    };

    $scope.$watchCollection('[model.calibrationCycle, model.calibrationDate]', function () {
        //  if (newCollection != oldCollection) {

        var cycleValue = $scope.model.calibrationCycle * 1;

        if ($scope.model.calibrationCycle === 0) {
            $scope.model.nextDueDate = undefined;
        } else {
            $scope.model.nextDueDate = new Date($scope.model.calibrationDate.getTime());
            $scope.model.nextDueDate.setMonth($scope.model.nextDueDate.getMonth() + cycleValue);
        }

        //  }
    });

    if ($stateParams.id) {
        Restangular.one('transaction', $stateParams.id).get().then(function (model) {
            $scope.model = model;
            model.calibrationDate = new Date(model.calibrationDate);
        });
    } else if ($stateParams.model) {
        // it's copy mode
        $scope.model = JSON.parse($stateParams.model);
    }

    $scope.update = function (model) {
        model.updatedBy = Constants.accountInfo.id;
        model.certifiedBy = Constants.accountInfo.fullName;
        return model.put({ id: model.certificateId }).then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.createdBy = Constants.accountInfo.id;
        model.updatedBy = Constants.accountInfo.id;
        model.certifiedBy = Constants.accountInfo.fullName;
        return Restangular.all('transaction').post(model).then(function (id) {
            $state.go('certificate-item', { id: id });
        });
    };

    $scope.copy = function () {
        var model = Restangular.stripRestangular($scope.model);

        toaster.pop('info', "Info", 'Prepared a copy version of certificated no. ' + model.certificateNo);

        model.certificateId = undefined;
        model.certificateNo = undefined;

        $state.go('certificate-new', {
            model: JSON.stringify(model)
        });
    };

    $scope.remove = function (model) {
        return model.remove({ id: model.certificateId }).then(function () {
            history.back();
        });
    };

    $scope.addRow = function (model) {
        var newRow = angular.copy(model);

        $scope.model.standards.push(newRow);

        $scope.newRow = undefined;
    };

    $scope.removeRow = function (index) {
        $scope.model.standards.splice(index, 1);
    };

    $scope.back = function () {
        history.back();
    };

    $scope.statuses = Statuses.map(function (value) {
        var ordinal = $filter('ordinal');
        value.text = ordinal(value.text);
        return value;
    });

    $scope.Cycles = [
       {
           value: 0,
           text: '0 month'
       },
       {
           value: 3,
           text: '3 months'
       },
       {
           value: 6,
           text: '6 months'
       },
       {
           value: 12,
           text: '12 months'
       },
       {
           value: 24,
           text: '24 months'
       }
    ];

    $scope.showStatus = function (value) {
        var result = '';

        if (value) {
            var selected = $filter('filter')($scope.statuses, { value: value });

            if (selected.length) {
                result = selected[0].text;
            }
        }

        return result;
    };

    $scope.updateStandard = function (item) {
        if (!item) {
            $scope.model.customer = {};
        } else if (typeof (customer) === 'object') {
            $scope.model.customer = customer;
        }
    };

    $scope.getStandardList = function (standardNo) {
        return Restangular.all('standard').getList({
            standardNo: standardNo
        });
    }
});